<?php
namespace Services\Login\Models;

use Admin\Models\BaseModel;
use Helpers\Main;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Services\UserService;

class XhsysUser extends BaseModel
{

    /**
     *
     * @var string
     */
    public $iUserId;

    /**
     *
     * @var string
     */
    public $sUserName;

    /**
     *
     * @var string
     */
    public $sLogonName;

    /**
     *
     * @var string
     */
    public $sLogonPwd;

    /**
     *
     * @var string
     */
    public $sSelfPhone;

    /**
     *
     * @var string
     */
    public $sEmailAddress;

    /**
     *
     * @var string
     */
    public $sQQNum;

    /**
     *
     * @var integer
     */
    public $iUserType;

    /**
     *
     * @var string
     */
    public $sRoles;

    /**
     *
     * @var integer
     */
    public $iUserSex;

    /**
     *
     * @var integer
     */
    public $iSchoolId;

    /**
     *
     * @var string
     */
    public $sExtraSchoolId;

    /**
     *
     * @var string
     */
    public $sIdentityCode;

    /**
     *
     * @var integer
     */
    public $iGradeCode;

    /**
     *
     * @var string
     */
    public $sAdClsName;

    /**
     * @var string
     */
    public $sSubject;

    /**
     *
     * @var integer
     */
    public $iStudStatus;

    /**
     *
     * @var string
     */
    public $sNationName;

    /**
     *
     * @var string
     */
    public $sBirthday;

    /**
     *
     * @var integer
     */
    public $bCompleted;

    /**
     *
     * @var integer
     */
    public $bMobileVerified;

    /**
     *
     * @var integer
     */
    public $bEbook;

    /**
     *
     * @var integer
     */
    public $bEbookLock;

    /**
     *
     * @var integer
     */
    public $iPoorLevel;

    /**
     *
     * @var integer
     */
    public $iDevSource;

    /**
     *
     * @var string
     */
    public $sSource;

    /**
     *
     * @var string
     */
    public $sPortrait;

    /**
     *
     * @var string
     */
    public $sMotherPhone;

    /**
     *
     * @var string
     */
    public $sFatherPhone;

    /**
     *
     * @var string
     */
    public $sOtherPhone;

    /**
     *
     * @var integer
     */
    public $iFirstPhone;

    /**
     *
     * @var string
     */
    public $oAddressInfo;

    /**
     *
     * @var string
     */
    public $oPwdQuestion;

    /**
     *
     * @var integer
     */
    public $bHistory;

    /**
     *
     * @var integer
     */
    public $bCompany;

    /**
     *
     * @var integer
     */
    public $bDisable;

    /**
     *
     * @var integer
     */
    public $bOldData;

    /**
     *
     * @var integer
     */
    public $bDelete;

    /**
     *
     * @var string
     */
    public $tCreateDate;

    /**
     *
     * @var string
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     */
    public $tLastModifyDate;

    /**
     *
     * @var string
     */
    public $iLastModifyUserId;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
        self::setup(['notNullValidations' => false]);
//        $this->hasOne(
//            'iUserId',
//            'XhsysUserstud',
//            "iUserId"
//        );
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHSys_User';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysUser[]|\Phalcon\Mvc\Model\ResultsetInterface
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysUser|\Phalcon\Mvc\Model
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    public function beforeSave()
    {
        $this->sRoles = self::getRoles($this->iUserType);
        //更改姓名通知用户服务
        if ($this->hasSnapshotData() && $this->hasChanged(['sUserName'])) {
            UserService::changeName($this->iUserId, $this->sUserName);
        }
        return true;
    }

    public function beforeCreate()
    {
        $this->iSchoolId === null and $this->iSchoolId = 1;
        $this->bCompany === null and $this->bCompany = 0;
        $this->bDisable === null and $this->bDisable = 0;
        $this->bHistory === null and $this->bHistory = 0;
        $this->sLogonName = trim($this->sLogonName);
        return parent::beforeCreate();
    }

    /**
     * 根据中文获取性别代码
     *
     * @param $name
     * @return int
     *
     * create by ck 20180913
     */
    public static function getSexCode($name)
    {
        switch ($name) {
            case '男':
                return 1;
            case '女':
                return 2;
            default:
                return 0;
        }
    }

    /**
     * 附带更改老库
     *
     * @return bool
     * @throws \Exception
     *
     * create by ck 20180504
     */
    public function saveWithOldData()
    {
        return $this->save();


        if ($this->iUserId != 26727 && $this->hasSnapshotData() && $this->hasChanged(['sUserName', 'sLogonName', 'iUserType', 'iSchoolId', 'sLogonPwd', 'sAdClsName', 'sSelfPhone'])) {
            static $oldDB = null;
            if (!$oldDB) {
                $oldDB = new Mysql(Main::getConfigByName('oldCenterDB'));
                if (!$oldDB) {
                    throw new \Exception('数据中心连接失败');
                }
            }
            $result = $oldDB->updateAsDict('users', [
                'us_name'       => $this->sUserName ?: '',
                'us_uid'        => $this->sLogonName,
                'us_flag'       => $this->iUserType,
                'us_school_xxid'=> $this->iSchoolId ?: 1,
                'us_passwd'     => $this->sLogonPwd,
                'us_szbj'       => $this->sAdClsName ?: '',
                'us_tel'        => $this->sSelfPhone ?: '',
            ], "us_id = '{$this->iUserId}'");
            if (!$result) {
                throw new \Exception('更新失败');
            }
        }
        return $this->save();
    }

    /**
     * 插入前写入到数据中心，检查是否存在
     *
     * @return bool
     * @param $oldSchool
     * @throws \Exception
     *
     * create by ck 20180427
     * modify by ck 20180514
     * modify by ck 20180521    支持更新老学校库
     * modify by ck 20180522    判断细化
     */
    public function insertAfterOld($oldSchool = false)
    {
        return $this->save();


        parent::beforeCreate();

        //检查用户名，手机号是否存在
        if ($this->sSelfPhone) {
            $check = self::count([
                'conditions' => 'bDelete = 0 AND (sLogonName = :logonName: OR sLogonName = :phone: OR sSelfPhone = :phone:)',
                'bind'       => ['logonName' => $this->sLogonName, 'phone' => $this->sSelfPhone]
            ]);
            if ($check > 0) {
                throw new \Exception('该手机号已存在');
            }
        }
        else {
            $check = self::count([
                'conditions' => 'bDelete = 0 AND sLogonName = :logonName:',
                'bind'       => ['logonName' => $this->sLogonName]
            ]);
            if ($check > 0) {
                if ($this->sLogonName == $this->sIdentityCode) {
                    throw new \Exception('该身份证号已存在');
                }
                throw new \Exception('该账号已存在');
            }
        }

        //老数据中心创建记录
        static $oldDB = null;
        if (!$oldDB) {
            $oldDB = new Mysql(Main::getConfigByName('oldCenterDB'));
            if (!$oldDB) {
                throw new \Exception('数据中心连接失败');
            }
        }
        $oldField = [
            'us_uid'        => $this->sLogonName,
            'us_name'       => $this->sUserName ?: '',
            'us_flag'       => $this->iUserType ?: 1,
            'us_school_xxid'=> $this->iSchoolId ?: 0,
            'us_passwd'     => $this->sLogonPwd,
            'us_date'       => $this->tCreateDate,
            'us_szbj'       => $this->sAdClsName ?: '',
            'us_tel'        => $this->sSelfPhone ?: '',
            'us_csrq' => '0000-00-00',
            'us_xb' => '',
            'us_mz' => '',
            'us_bmdq' => '',
            'us_sdxx' => '',
            'us_sdnj' => '',
            'us_qq' => '',
            'us_fmxm' => '',
            'us_jtgddh' => '',
            'us_fmsj' => '',
            'us_jtdz' => '',
            'us_fmdw' => '',
            'us_dwdz' => '',
            'us_bzsm' => '',
            'us_ord' => 0,
            'us_sskm' => '',
            'us_lastip' => '',
            'us_question' => '',
            'us_answer' => '',
            'us_lxxx' => '',
            'us_gsbz' => '',
            'us_us_id_power' => '',
            'us_province' => '',
            'us_city1' => '',
            'us_city2' => '',
            'us_fw_text' => '',
            'us_fdq_name' => '',
            'us_sfzx' => '',
            'us_us_id_power_ls' => '',
            'us_jf_dates' => '0000-00-00 00:00:00',
            'us_sq_dl_dates' => '0000-00-00 00:00:00',
            'us_sq_ls_dates' => '0000-00-00 00:00:00',
            'us_sales_sort' => '',
            'us_sq_fl_dates' => '0000-00-00 00:00:00',
            'us_fmsjm' => '',
            'us_xyh' => '',
            'us_domain' => '',
            'us_nickname' => '',
            'us_email' => '',
            'us_czy_id' => 0,
        ];
//        $result = $oldDB->insert('users', array_values($oldField), array_keys($oldField));
        $result = $oldDB->insertAsDict('users', $oldField);
        if (!$result) {
            throw new \Exception('老数据中心插入失败');
        }
        $userId = $oldDB->lastInsertId();
        $this->iUserId = $userId;

        //更新老学校库
//        try {
//            if ($oldSchool) {
//                $oldSchoolDBName = '';
//                $oldSchoolDB     = Main::getSchoolMainDB($this->iSchoolId, $oldSchoolDBName);
//                if ($oldSchoolDB) {
//                    $oldSchoolDB->insertAsDict('users', array_merge($oldField, ['us_id' => $userId]));
//                }
//            }
//        }
//        catch (\Exception $e) {}

        return $this->save();
    }

    /**
     * 根据用户类型获取用户角色
     *
     * @param $userType
     * @return string
     *
     * create by ck 20171212
     */
    public static function getRoles($userType)
    {
        switch ($userType){
            case 1: return 'student';
            case 2: return 'assistant';
            case 3: return 'agent';
            case 4: return 'teacher';
            case 5: return 'parents';
            case 6: return 'school_admin';
            case 7: return 'staff';
            case 8: return 'admin';
            default: return 'default';
        }
    }

    /**
     * 根据id数组删除用户信息并返回结果
     *
     * @param $idArr
     * @return mixed
     *
     * create by ck 20161010
     */
    public static function deleteRecordById($idArr)
    {
        return self::find(array(
            'conditions' => 'bDelete = 0 AND iUserId IN ({idArr:array})',
            'bind'       => ['idArr' => $idArr]
        ))->delete();
    }

    /**
     * 根据信息新建用户
     *
     * @param array $data
     * @return XhsysUser
     *
     * create by ck 20160630
     * modify by ck 20161010    化简
     */
    public static function createRecord($data)
    {
        $obj = $data['iUserId'] ? self::findFirst($data['iUserId']) : new self;
        $obj or $obj = new self();
        if($obj->sLogonPwd && !$data['sLogonPwd']) unset($data['sLogonPwd']);
        $obj->assign($data);
        $obj->iSchoolId or $obj->iSchoolId = 1;
        $obj->sBirthday or $obj->sBirthday = null;
        isset($data['sLogonPwd']) and $obj->sLogonPwd = strtoupper(md5($data['sLogonPwd']));
        return $obj;
    }

    /**
     * 根据登录名，密码或用户ID查询用户信息并返回
     *
     * @param $logonName
     * @param $password
     * @param $userId
     * @return XhsysUser
     *
     * create by ck 20161011
     * modify by ck 20170828    可使用手机号登陆
     */
//    public static function searchUserForLogin($logonName, $password, $userId = null)
//    {
//        if($userId){
//            return self::findFirst([
//                'conditions'    => 'iUserId = :iUserId: AND sLogonPwd = :sLogonPwd: AND bDisable = 0 AND bDelete = 0',
//                'bind'          => [
//                    'iUserId'       => $userId,
//                    'sLogonPwd'     => $password
//                ]
//            ]);
//        }
//        return self::findFirst([
//            'conditions'    => '(sLogonName = :sLogonName: OR sSelfPhone = :sLogonName:) AND sLogonPwd = :sLogonPwd: AND bDisable = 0 AND bDelete = 0',
//            'bind'          => [
//                'sLogonName'    => $logonName,
//                'sLogonPwd'     => $password
//            ]
//        ]);
//    }

    /**
     * 根据身份证查找用户信息
     *
     * @param $identityCode
     * @return XhsysUser
     *
     * create by ck 20160908
     */
    public static function selectUserByIdentity($identityCode)
    {
        return self::findFirst("sIdentityCode = '{$identityCode}' AND bDelete = 0");
    }

    /**
     * 根据ID获取用户姓名并组成数组返回
     *
     * @param $idArr
     * @return XhsysUser[]|array|bool
     *
     * create by ck 20170329
     * modify by ck 20171109
     */
    public static function getUserNameById($idArr)
    {
        if(!$idArr) return false;
        $idArr = array_merge(array_unique($idArr));
        $userInfo = self::find([
            'columns'    => 'iUserId,sUserName',
            'conditions' => 'iUserId IN ({idArr:array})',
            'bind'       => ['idArr' => $idArr]
        ]);
        if(!$userInfo) return [];
        $userInfo = array_column($userInfo->toArray(), 'sUserName', 'iUserId');
        return $userInfo;
    }

    /**
     * 根据ID获取用户登录名并组成数组返回
     *
     * @param $idArr
     * @return XhsysUser[]|array|bool
     *
     * create by ck 20180518
     */
    public static function getUserLogonName($idArr)
    {
        if(!$idArr) return false;
        $idArr = array_merge(array_unique($idArr));
        $userInfo = self::find([
            'columns'    => 'iUserId,sLogonName',
            'conditions' => 'iUserId IN ({idArr:array})',
            'bind'       => ['idArr' => $idArr]
        ]);
        if(!$userInfo) return [];
        $userInfo = array_column($userInfo->toArray(), 'sLogonName', 'iUserId');
        return $userInfo;
    }

}
